package com.xuxk.project.library.controller;

import com.xuxk.project.util.ErrResponseBodyVo;
import com.xuxk.project.util.ErrorCodeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xuxk
 * 错误异常处理控制类
 */
@RestController
@RequestMapping("/error")
public class BaseErrorController implements ErrorController {

    private static final String PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

    @Value("${spring.application.name}")
    private String applicationName;

    @Override
    public String getErrorPath() {
        return PATH;
    }

    @RequestMapping
    public ErrResponseBodyVo error(HttpServletRequest  request, HttpServletResponse response) {

        ErrResponseBodyVo errResponseBody=new ErrResponseBodyVo();
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        Exception exception=(Exception) request.getAttribute("javax.servlet.error.exception");
        if( exception!=null && (exception.getCause() instanceof ErrorCodeException))
        {
            int code = ((ErrorCodeException) exception.getCause()).getCode();
            errResponseBody.setCode(code);
            errResponseBody.setMsg(((ErrorCodeException) exception.getCause()).getMsg());
        }else if(exception.getCause() instanceof  IllegalArgumentException){
            Exception exception1 = ((IllegalArgumentException) exception.getCause()) ;
            errResponseBody.setCode(1001);
            errResponseBody.setMsg(exception1.getMessage());
        }
        else
        {
            errResponseBody.setCode(statusCode);
            errResponseBody.setMsg(HttpStatus.valueOf(statusCode).getReasonPhrase());
        }
        errResponseBody.setSys(applicationName);
        return errResponseBody;
    }




}
